﻿$(document).ready(function() {
	// 手机号码和邮箱验证
	jQuery.validator.addMethod("isTrue", function(value, element) {
		var length = value.length;
		return this.optional(element) || (length == 11 && /^1(3[0-9]|4[457]|5[0-35-9]|7[0135678]|8[0-9])[0-9]{8}$/.test(value)) ||  (/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value));
	}, "请正确填写手机号码或者邮箱。");
    // 手机号码验证
    jQuery.validator.addMethod("isPhone", function(value, element) {
        var length = value.length;
        return this.optional(element) || (length == 11 && /^1(3[0-9]|4[457]|5[0-35-9]|7[0135678]|8[0-9])[0-9]{8}$/.test(value));
    }, "请正确填写手机号码。");
    jQuery.validator.addMethod("isVerification", function(value, element) {
        return this.optional(element) || (/^\d{4,6}$/.test(value));
    }, "请正确填写验证码。");
	// 匹配密码，长度在6-12之间。
	jQuery.validator.addMethod("isPwd", function(value, element) {
		var str = value;
		return this.optional(element) || (/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/.test(str));
	}, "请填写6-16位字母/数字组合。");

	$("#userForm").validate({
		errorElement : 'span',
		errorClass : 'help-block',

		rules : {
            username : {
                required : true,
                isTrue : true
            },
			password : {
				required : true,
				isPwd : true
			},
			confirm_password : {
				required : true,
				isPwd : true,
				equalTo : "#password"
			},
            phone : {
                required : true,
                isPhone : true
            },
            code: {
                required : true,
                isVerification : true
			}
		},
		messages : {
			username : {
                required : "请输入手机号或者邮箱",
            },
			password : {
				required : "请输入密码",
				minlength : jQuery.format("密码不能小于{0}个字 符")
			},
			confirm_password : {
				required : "请输入确认密码",
				minlength : "确认密码不能小于6个字符",
				equalTo : "两次输入密码不一致"
			},
			phone : {
				required : "请输入手机号码",
			},
            code : {
                required : "请输入验证码",
            }
		},
		errorPlacement : function(error, element) {
			element.next("span").remove();
			element.after('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
			element.closest('.form-group').append(error);
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error has-feedback');
		},
		success : function(label) {
			var el=label.closest('.form-group').find("input");
			el.next("span").remove();
			el.after('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
			label.closest('.form-group').removeClass('has-error').addClass("has-feedback has-success");
			label.remove();
		},
		submitHandler: function(form) {
            regist();
		}
	});
});

